#include "LevelSelectScreen.h"
#include "SimpleAudioEngine.h"
#include "../Levels/LevelLoader.h"
#include "../Levels/Level.h"
#include "../Supporting/Enums/EnumScreenType.h"
#include "../Supporting/PlayerData.h"
#include "../FlowController.h"

using namespace cocos2d;
using namespace CocosDenshion;

//===== CONSTRUCTOR =====
LevelSelectScreen::LevelSelectScreen() : BaseScreen()
{
	_screenID = SCREEN_LEVELSELECT;

	_bgFileName = CCString::create("Menu/Levels/[BG] Level Selection.png");

	_lockFactor = 1;
	_levelSelected = 0;
	_levelButtons = new CCArray();
}
//===== DESTRUCTOR =======
LevelSelectScreen::~LevelSelectScreen()
{
	_levelButtons->release();
	_levelButtons = NULL;

	if (myLevelLoader != 0)
		delete myLevelLoader;
}

/*
 * @function: createLayer
 * @brief: Create MainMenuScreen layer
 * @return: MainMenuScreen layer
 */
BaseScreen* LevelSelectScreen::createLayer()
{
    // 'layer' is an autorelease object
	LevelSelectScreen *layer = LevelSelectScreen::create();

	layer->setLevelLoaderReference(new LevelLoader());

    // return the scene
    return layer;
}

/*
 * @function: loadScreen
 * @brief: Load the screen for main menu screen
 * @param flowcontroller: reference to FlowController
 * @param bgfilename: filename to the background image
 * @result: create the main menu screen
 */
void LevelSelectScreen::loadScreen(FlowController *flowcontroller)
{
	BaseScreen::loadScreen(flowcontroller);

	CCSize _screenSize = CCDirector::sharedDirector()->getWinSize();

	//==========================BACKGROUND============================
	CCSprite *bgTitle = CCSprite::create("Menu/Levels/[Text] Level Select.png");
	bgTitle->setScale(_scaleFactor);
	bgTitle->setPosition(ccp(_screenSize.width/2,_screenSize.height-(60*_scaleFactor)));
	this->addChild(bgTitle);

	//========================= MAP ==================================
	//Retrieve levels from levelloader
	levelList = myLevelLoader->getLevelList();

	for( int i = 0 ; i < 7 ; i++ )
	{
		CCSprite *baselevel = CCSprite::create("Menu/Levels/[UI] Level Select Grid.png");
		baselevel->setScale(_scaleFactor);
		baselevel->setPosition(ccp(((i*128+200)*_scaleFactor),_screenSize.height/2));

		_levelButtons->addObject(baselevel);
		this->addChild(baselevel);

		if( i >= _lockFactor )
		{
			CCSprite *lock = CCSprite::create("Menu/Levels/[UI] Lock.png");
			lock->setScale(_scaleFactor);
			lock->setPosition(ccp(baselevel->getPositionX(),baselevel->getPositionY()+50*_scaleFactor));
			this->addChild(lock);
		}
	}

	CCSprite *character = CCSprite::createWithSpriteFrame(CCSpriteFrame::create("Game/Character/[Human][Engineer] (100).png", CCRect(0, 0, 100, 100)));
	CCAnimation *runningAnimation = CCAnimation::create();
	//load the frames of animation
	for (int i = 0; i < 4; i++)
	{
		CCSpriteFrame *frame = CCSpriteFrame::create("Game/Character/[Human][Engineer] (100).png", CCRect(i*100, 0, 100, 100));
		runningAnimation->addSpriteFrame(frame);
	}
	//setup animation properties
	runningAnimation->setDelayPerUnit(0.15); // delay between each frame in seconds
	runningAnimation->setLoops(10000);
	runningAnimation->setRestoreOriginalFrame(true); //loop

	//start animating the running
	character->setScale(_scaleFactor);
	character->setPosition(ccp(200*_scaleFactor,_screenSize.height/2+(90*_scaleFactor)));
	character->runAction(CCAnimate::create(runningAnimation));
	character->setFlipX(true);
	character->setTag(100);
	this->addChild(character);

	//=========================SKILL BAR============================
	CCSprite *levelscorebar = CCSprite::create("Menu/Levels/[UI] Level Select - Escape.png");
	levelscorebar->setScale(_scaleFactor);
	levelscorebar->setPosition(ccp(_screenSize.width/2,_screenSize.height/2 - (250*_scaleFactor)));
	this->addChild(levelscorebar);

	//================BUTTONS======================
	//Start button
	CCSprite * backButtonSprite = CCSprite::create("Menu/Skills/[Button] Back - Normal.png");
	CCSprite * backButtonSpritePressed = CCSprite::create("Menu/Skills/[Button] Back - Pressed.png");
	CCMenuItemSprite* backButton = CCMenuItemSprite::create(backButtonSprite,backButtonSpritePressed,this,menu_selector(LevelSelectScreen::backButtonPressed));
	backButton->setScale(_scaleFactor);
	backButton->setPosition(ccp((50*_scaleFactor),(50*_scaleFactor)));

	CCSprite * playButtonSprite = CCSprite::create("Menu/Skills/[Button] Play - Normal.png");
	CCSprite * playButtonSpritePressed = CCSprite::create("Menu/Skills/[Button] Play - Pressed.png");
	CCMenuItemSprite* playButton = CCMenuItemSprite::create(playButtonSprite,playButtonSpritePressed,this,menu_selector(LevelSelectScreen::playButtonPressed));
	playButton->setScale(_scaleFactor);
	playButton->setPosition(ccp(_screenSize.width/2 + (295*_scaleFactor),(65*_scaleFactor)));

    CCMenu* mainmenu = CCMenu::create(playButton, backButton, NULL);
    mainmenu->setPosition(0,0);
    //mainmenu->setTag(MAINMENU);
	this->addChild(mainmenu);

    //======================== LEVEL TITLE =======================
	CCLabelTTF * font = CCLabelTTF::create(levelList[0]->getLevelName()->getCString(), "Font/CarterOne.ttf", 30*_scaleFactor);
	font->setAnchorPoint(ccp(0,0));
	font->enableStroke(ccc3(0,0,0),2,true);
	font->setPosition(ccp(_screenSize.width/2-240*_scaleFactor,37*_scaleFactor));
	font->setTag(101);
	this->addChild(font);

	int currenthighscore = PlayerData::getLevelScore(1);
	CCString *highscorestring = CCString::createWithFormat("%d",currenthighscore);
	CCLabelTTF * font2 = CCLabelTTF::create(highscorestring->getCString(), "Font/CarterOne.ttf", 25*_scaleFactor);
	font2->setAnchorPoint(ccp(0,0));
	font2->enableStroke(ccc3(0,0,0),2,true);
	font2->setPosition(ccp(_screenSize.width/2-(168*_scaleFactor),(88*_scaleFactor)));
	this->addChild(font2);
}


/*!
 * @function: ccTouchesBegan
 * @brief: Cocos2d-x default library for touches began, this function is called for every touch that touch the device's screen
 */
void LevelSelectScreen::ccTouchesBegan(CCSet* touches, CCEvent* event)
{
	CCTouch* touch = (CCTouch*)(touches->anyObject());
	CCPoint location = touch->getLocationInView();
	location = CCDirector::sharedDirector()->convertToGL(location);

	for( int i = 0 ; i < _levelButtons->count() ; i++ )
	{
		if( i >= _lockFactor )
			break;

		CCSprite *base = (CCSprite*)_levelButtons->objectAtIndex(i);

		if( base->boundingBox().containsPoint(location) && i != _levelSelected )
		{
			//Shift the character
			CCSprite *character = (CCSprite*)this->getChildByTag(100);
			character->setPosition(ccp(base->getPositionX(),base->getPositionY()+(90*_scaleFactor)));

			CCLabelTTF *word = (CCLabelTTF*)this->getChildByTag(101);
			word->setString(levelList[i]->getLevelName()->getCString());

			//update the level
			_levelSelected = i;

			break;
		}
	}
}


/*
 * @function: returnToPreviousScreen
 * @brief: function to return back to main menu screen when back button is pressed
 * @result: return to main menu screen
 */
void LevelSelectScreen::returnToPreviousScreen()
{
	_myFlowController->switchScreenTo(SCREEN_MAIN);
}

/*
 * @function: keyBackClicked
 * @brief: hardware back button function
 * @result: return to main menu screen
 */
void LevelSelectScreen::keyBackClicked()
{
	returnToPreviousScreen();
}

/*
 * @function: backButtonPressed
 * @brief: UI back button pressed
 * @result: return to main menu screen
 */
void LevelSelectScreen::backButtonPressed()
{
	returnToPreviousScreen();
}
/*
 * @function: playButtonPressed
 * @brief: Proceed to GameManager scene, skill data are also saved
 */
void LevelSelectScreen::playButtonPressed()
{
	//save level selected
	PlayerData::saveSelectedLevel(_levelSelected+1); //levels is 1-based
	//Go to game
	_myFlowController->switchScreenTo(SCREEN_SKILLSELECT);
}
